package com.scrx.ymg.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scrx.ymg.dao.head.IHeadDao;
import com.scrx.ymg.dao.orderform.IOrderFormDao;
import com.scrx.ymg.dao.product.IProductDao;
import com.scrx.ymg.entity.Address;
import com.scrx.ymg.entity.HeadMoney;
import com.scrx.ymg.entity.OrderForm;
import com.scrx.ymg.entity.OrderFormDetails;
import com.scrx.ymg.entity.OrderReturn;
import com.scrx.ymg.entity.ProductEvaluate;
import com.scrx.ymg.entity.SuperMarketEntrepot;
import com.scrx.ymg.entity.SuperMarketInfo;
import com.scrx.ymg.entity.User;
import com.scrx.ymg.entity.UserComplain;
import com.scrx.ymg.service.address.IAddressService;
import com.scrx.ymg.service.orderform.IOrderFormService;
import com.scrx.ymg.service.supermarket.ISuperMarketService;
import com.scrx.ymg.service.user.IUserService;
import com.scrx.ymg.util.PayConfigUtil;
import com.scrx.ymg.utilqy.CollectionUtil;
import com.scrx.ymg.utilqy.HttpUtils;
import com.scrx.ymg.utilqy.JsonResult;
import com.scrx.ymg.utilqy.PayUtil;
import com.scrx.ymg.utilqy.ResponseData;
import com.scrx.ymg.utilqy.SerializerFeatureUtil;
import com.scrx.ymg.utilqy.WebUtil;
import com.scrx.ymg.utilqy.XmlUtil;

@Controller
@RequestMapping("/orderFormAction")
public class OrderFormAction {
	@Autowired
	private IOrderFormService  ofs;
	@Autowired
	private IUserService  users;
	@Autowired
	private IAddressService adds;
	@Autowired
	private ISuperMarketService  sms;
	@Autowired
	private IOrderFormDao orderFormDao;
	@Autowired
	private IHeadDao headao;
	@Autowired
	private IProductDao productDao;
	
	private static final Logger LOG = Logger.getLogger(TransferController.class);

    private static final String TRANSFERS_PAY = "https://api.mch.weixin.qq.com/secapi/pay/refund"; // 退款

    private static final String APP_ID = PayConfigUtil.APPID;

    private static final String MCH_ID = PayConfigUtil.MCH_ID;

    //private static final String API_SECRET =PayConfigUtil.APP_SECRET;
    
    private static final String TGRefund_URL =PayConfigUtil.TGRefund_URL;
    
	/**
	 * 根据状态分组查询订单头数量
	 */
	@ResponseBody
	@RequestMapping(value ="/getOrderFormNum",produces = "text/json;charset=UTF-8")
	//查询所有订单数量
	public String getOrderFormNum(String userID){
		Gson gson = new Gson();
		List list=ofs.getOrderFormGroupStatus(userID);
			if(list.size()>0){
				return gson.toJson(list);
			}
		return "false";
	}
	
	/**
	 * 购买商品生成订单
	 * @param userID 用户ID
	 * @param superID 超市ID
	 * @param productjson 商品列表
	 * @param addjson  地址信息
	 * @param shipping_fee 配送费
	 * @param totalMoney  总金额
	 * @param paymentType  付款方式
	 */
		@ResponseBody
		@RequestMapping(value ="/shoppingToSuperMarket",produces = "text/json;charset=UTF-8")
		public String  shoppingToSuperMarket(String userID,String superID,String detailsjson,String addressID,double shipping_fee,double totalMoney,int paymentType){
			String msg="false";
			//消费者到超市购买商品
			Gson gson = new Gson();
			//1.得到消费者信息
			User user=users.findById(Integer.parseInt(userID));
			if(user!=null){
				//2.1得到超市信息
				SuperMarketInfo superinfo=sms.findByID(Integer.parseInt(superID));
				//2.2得到地址信息,
				Address add=adds.getAddressByID(addressID);
                if(add.getSuperId()!=Integer.parseInt(superID)){
						  return "false";
			   }
				//3.得到商品信息
				List<OrderFormDetails> details =gson.fromJson(detailsjson, new TypeToken<List<OrderFormDetails>>() {}.getType());
				//4.生成订单
				msg=ofs.createOrderForm(user, superinfo, add, shipping_fee,totalMoney, paymentType,details,1);
			}
			return msg;
		}
		
		/**
		 * 根据用户查询对应状态的订单详情
		 * @param userid 用户id
		 * @param status 订单状态
		 * @return json 对应订单
		 */
		@ResponseBody
		@RequestMapping(value ="/getOrderFormByStatus",produces = "text/json;charset=UTF-8")
		public String getOrderFormByStatus(String userid,String status){
			Gson gson = new Gson();
			List<OrderForm> list=ofs.getOrderFormByStatus(userid, status);
			return gson.toJson(list);
		}
		
		/**
		 * 根据用户查询全部订单
		 * @param userID 用户ID
		 * @return json 对应订单
		 */
		@ResponseBody
		@RequestMapping(value ="/getOrderFormByUserID",produces = "text/json;charset=UTF-8")
		public String getOrderFormByUserID(String userID){
			Gson gson = new Gson();
			List<OrderForm> list=ofs.getOrderFormByUserID(userID);
			return gson.toJson(list);
		}
		/**
		 * 根据超市id查询所属状态订单
		 * @param superID 用户ID
		 * @param status 订单状态
		 * @return json 对应订单
		 */
		@ResponseBody
		@RequestMapping(value ="/getOrderFormBySuper",produces = "text/json;charset=UTF-8")
		public String getOrderFormBySuper(OrderForm orderform,int pageNum,int pageCount){
			Map<Object, Object> map=ofs.getOrderFormBySuper(orderform,pageNum,pageCount);
			Gson gson = new Gson();
			return gson.toJson(map);
		}
		
		/**
		 * 查询所属状态订单
		 * @param superID 用户ID
		 * @param status 订单状态
		 * @return json 对应订单
		 */
		@ResponseBody
		@RequestMapping(value ="/getOrderFormBySuperInfo",produces = "text/json;charset=UTF-8")
		public String getOrderFormBySuperInfo(OrderForm orderform,String startTime,String endTime,int pageNum,int pageCount){
			Map<Object, Object> map=ofs.getOrderFormBySuper(orderform,startTime,endTime,pageNum,pageCount);
			Gson gson = new Gson();
			return gson.toJson(map);
		}
		
		
		/**
		 * 用户确认收货
		 * @param userID
		 * @param orderFormID  订单头ID
		 * @return 
		 */
		@ResponseBody
		@RequestMapping(value ="/takeDeliveryOfGoods",produces = "text/json;charset=UTF-8")
		public String takeDeliveryOfGoods(String userID,int id){
			    String   judge = ofs.directTakeDeliveryYongJin(id);  
			return judge;
		}
		
		/**
		 * 超市后台发货
		 * @param superID
		 * @param orderFormID
		 * @return
		 */
		@ResponseBody
		@RequestMapping(value ="/TheSupermarketDelivery",produces = "text/json;charset=UTF-8")
		public String TheSupermarketDelivery(String orderFormID){
			return ofs.TheSupermarketDelivery(orderFormID,null);
		}
		
		/**
		 * 消费者取消订单
		 * @param order
		 * @return
		 */
		@ResponseBody
		@RequestMapping(value ="/cancelOrderForm",produces = "text/json;charset=UTF-8")
		public String cancelOrderForm(OrderForm order){
			return ofs.cancelOrderForm(order);
		}
		
		/**
		 * 消费者退货
		 * @param order
		 * @return
		 */
		@ResponseBody
		@RequestMapping(value ="/returnsOrderForm",produces = "text/json;charset=UTF-8")
		public String returnsOrderForm(OrderForm order){
			return ofs.returnsOrderForm(order);
		}
		
		/**
		 * 消费者评价订单
		 * @param order
		 * @param peva
		 * @return
         */
		@ResponseBody
		@RequestMapping(value ="/evaluateOrderForm",produces = "text/json;charset=UTF-8")
		public String evaluateOrderForm(int orderId,int userId,ProductEvaluate peva){
			return ofs.evaluateOrderForm(orderId,userId,peva);
		}
		
		/**
		 * 消费者投诉订单
		 * @param order
		 * @param com
		 * @return
		 */
		@ResponseBody
		@RequestMapping(value ="/complaintOrderForm",produces = "text/json;charset=UTF-8")
		public String complaintOrderForm(OrderForm order,UserComplain com){
			return ofs.complaintOrderForm(order,com);
		}
		
		/**
		 * 消费者催单
		 * @param superID
		 * @return 配送电话
		 */
		@ResponseBody
		@RequestMapping(value ="/reminder",produces = "text/json;charset=UTF-8")
		public String reminder(int superID){
			return ofs.reminder(superID);
		}
		
		/**
		 * 超市查询退货信息
		 * @param superID
		 * @return 配送电话
		 */
		@ResponseBody
		@RequestMapping(value ="/userReturn",produces = "text/json;charset=UTF-8")
		public String userReturn(OrderReturn order,int pageCount,int pageNum){
			Gson gson = new Gson();
			Map<Object,Object> map = ofs.getUserReturn(order,pageCount,pageNum);
			String str=gson.toJson(map);
			return str;
		}
		/**
		 * 货到付款退货
		 * @param orderFormID
		 * @return
		 */
		@ResponseBody
		@RequestMapping(value ="/disposeReturn",produces = "text/json;charset=UTF-8")
		public String disposeReturn(String orderFormID){
			return ofs.disposeReturn(orderFormID);
		}
		
		/**
		 * 处理退货请求
		 * @return
		 */
		@ResponseBody
		@RequestMapping(value ="/returnTransferPay",produces = "text/json;charset=UTF-8")
		public void returnTransferPay(String TransferNo,HttpServletRequest request, HttpServletResponse response){
			LOG.info("退款单号:"+TransferNo);
	        //判断订单是否能够退款
	        Map<String, String> restmap = null;
	        OrderForm order=null;
	        boolean returnMsg=false;
	        try {
	        	 order = ofs.getOrderFormByOrderId(TransferNo);
	        	 if(order.getTypeId()==3&&order.getParent()!=null&&order.getParent()>0){
	        		 OrderForm sub = ofs.getOrderFormById(order.getParent());
	        	 }
	        	//User user = users.findById(order.getUserId());
	            Double total_fee = order.getTotalMoney()*100;
	            Map<String, String> parm = new HashMap<String, String>();
	            parm.put("appid", APP_ID); //公众账号appid
	            parm.put("mch_id", MCH_ID); //商户号
	            parm.put("op_user_id",MCH_ID); 
	            parm.put("nonce_str", PayUtil.getNonceStr()); //随机字符串
	            if(order.getTypeId()==3&&order.getParent()!=null&&order.getParent()>0){
	       		 OrderForm sub = ofs.getOrderFormById(order.getParent());
	       		Double total_fee2 = sub.getTotalMoney()*100;
	       		parm.put("out_trade_no",sub.getOrderFormId().toString()); //商户订单号
	       		parm.put("total_fee", total_fee2.intValue()+""); //订单金额
	       	    }else{
	       	    parm.put("out_trade_no",order.getOrderFormId().toString()); //商户订单号
	       	    parm.put("total_fee", total_fee.intValue()+""); //订单金额
	       	    }
	            parm.put("out_refund_no",order.getOrderFormId().toString()); //商户退货订单号
	            parm.put("refund_fee", total_fee.intValue()+""); //退款金额
	            parm.put("sign", PayUtil.getSign(parm, PayConfigUtil.API_KEY));
				String restxml = HttpUtils.posts(TRANSFERS_PAY, XmlUtil.xmlFormat(parm, false));
				restmap = XmlUtil.xmlParse(restxml);
	        } catch (Exception e) {
	            LOG.error(e.getMessage(), e);
	        }
	        if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
	            LOG.info("退款成功：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
	            Map<String, String> transferMap = new HashMap<>();
	            transferMap.put("partner_trade_no", restmap.get("partner_trade_no"));//商户转账订单号
	            transferMap.put("payment_no", restmap.get("payment_no")); //微信订单号
	            transferMap.put("payment_time", restmap.get("payment_time")); //微信支付成功时间

	            String msg =ofs.returnTransferPay(TransferNo);
	            LOG.info("退款成功-订单状态修改:"+msg);
	            if(msg.equals("true")){
	            	WebUtil.response(response,
		                    WebUtil.packJsonp(TGRefund_URL,
		                            JSON.toJSONString(new JsonResult(1, "退货成功", new ResponseData(null, transferMap)),
		                                    SerializerFeatureUtil.FEATURES)));
	            }else{
	            	WebUtil.response(response,
		                    WebUtil.packJsonp(TGRefund_URL,
		                            JSON.toJSONString(new JsonResult(1, "请刷新页面", new ResponseData(null, transferMap)),
		                                    SerializerFeatureUtil.FEATURES)));
	            }
	        }else {
	            if (CollectionUtil.isNotEmpty(restmap)) {
	                LOG.info("退款失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
	            }
	            WebUtil.response(response, WebUtil.packJsonp(TGRefund_URL, JSON
	                    .toJSONString(new JsonResult(-1, "退货失败", new ResponseData()), SerializerFeatureUtil.FEATURES)));
	        }
		}
		
		/**
		 * 根据订单id查询订单详情
		 * @return
		 */
		@ResponseBody
		@RequestMapping(value ="/getOrderFormDetailsByOrderFormID",produces = "text/json;charset=UTF-8")
		public String getOrderFormDetailsByOrderFormID(String orderFormId){
			List<OrderFormDetails> list = ofs.getOrderFormDetailsByOrderFormID(orderFormId);
			Gson gson = new Gson();
			String str=gson.toJson(list);
			return str;
		}
}
